<?php
namespace App\Http\Controllers\WebApi\Common;
use Illuminate\Routing\Controller;
use App\Common\ErrorCode\ErrorCode;
use App\Common\Output\JsonOutput;
use App\Exceptions\BusinessException;
class BaseController extends Controller
{
    protected $web_access = 'qSoiKwpWVge4TkaryH6MKvOdceGt7ZMaF20g8H0cnXI'; //接口调用权限

    /**
     * 接口基本控制器
     */

    public function __construct()
    {
        //parent::__construct();
    }

    /**
     * 返回到手机端的数据格式
     * 制作者：九哥
     * code错误代号，dataArr返回的数据
     * code：0操作成功，
     */
    public function toJson($code=0,$dataArr=array())
    {
        $msgArr = array(
            0 => '操作成功', -1 => '接口权限错误', -2 => '参数错误',
            -3 => '没有数据', -4 => '用户已存在', -5 => 'TOKEN错误',
            -7 =>'验证码错误',//zwp,增加一个配置
            -8 =>'用户类型不能更改',
            -99 =>'非法请求',
            -100 => '操作失败',
        );
        $json = array(
            'code' => $code,
            'msg' => $msgArr[$code].'！',
        );
        if ($dataArr) { $json['data'] = $dataArr; }
        return $json;
    }

    public function output($data = [], $msg = "ok",
                           $code = 200, $status = 200,
                           array $headers = [], $options = 0)
    {
        $headers['Access-Control-Allow-Origin'] = '*';
        return response()->json(compact('msg', 'code', 'data'), $status, $headers, $options);
    }


    /**
     * @param array $data
     */
    public function success(array $data = [])
    {
        JsonOutput::success($data);
    }

    /**
     * @param array $data
     */
    public function error(int $code = 0, string $message = "")
    {
        JsonOutput::error($code, $message);
    }


    /**
     * @param Request $request
     * @param array $rules
     * @throws BusinessException
     */
    public function webParamValidate(Request $request, $rules = [])
    {
        try{
            $this->validate($request, $rules);
        }catch (ValidationException $exception) {
            throw new BusinessException(ErrorCode::ERROR_PARAM, '参数错误：'.array_values($exception->errors())[0][0]);
        }catch (\Exception $exception){
            throw new BusinessException(ErrorCode::ERROR_SERVER_UNKNOWN, '服务端校验参数时发生错误');
        }
    }
}
